//
//  ZHLEEHomeViewController.swift
//  ZHLEEBlog_swift_pro
//
//  Created by ZHLEEBlander on 15/10/9.
//  Copyright © 2015年 ZHLEEBlander. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class ZHLEEHomeViewController: UITableViewController {
// MARK: - 
// MARK: -----------属性-------------------
    //重用ID
    private let Cell_ID = "home_cell"
    /// 数据
    lazy var statusArray:[ZHLEEStatusFrame] = [ZHLEEStatusFrame]()
    
    private lazy var pullupView: UIActivityIndicatorView = {
    
        //初始化加载view
        let pullupView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        pullupView.color = UIColor.redColor()
        
        return pullupView
    }()
    /// 加载数据后显示label
    private lazy var pullDownTipLabel: UILabel = {
    
        let label = UILabel()
        //背景色
        label.backgroundColor = UIColor.orangeColor()
        //字体,字体颜色
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.whiteColor()
        //文字居中
        label.textAlignment = NSTextAlignment.Center
        
        label.text = "没有新的微博信息"
        
        label.hidden = true
        
        return label
    }()
    
// MARK: - 
// MARK: viewDidLoad----------方法------------
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavItem()
        
        setupTableView()
        /**
        设置新消息提示
        */
//        self.tabBarItem.badgeValue = "9999"
        
    }
    
    private func setupTableView(){
    
        //注册cell
        self.tableView.registerClass(ZHLEEStatusCell.self, forCellReuseIdentifier: Cell_ID)
        
        //为tableView加个背景颜色
        self.tableView.backgroundColor = RGB(r: 240, g: 240, b: 240)
        
        //去掉分割线
        tableView.separatorStyle = .None
        
        //上拉加载view设置
        self.tableView.tableFooterView = pullupView
        
        //下拉刷新控件
        self.refreshControl = UIRefreshControl()
        self.refreshControl?.addTarget(self, action:"loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        /**
        加载数据
        */
        loadData()
    }
    /**
    加载数据
    */
    @objc private func loadData(){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var params = [String: AnyObject]()
        
        if pullupView.isAnimating(){
        
            if let statusFrame = statusArray.last{
            
                //取当前界面上的最后一条微博
                params["max_id"] = "\(statusFrame.status!.id - 1)"
            }
        }else{
        
            if let statusFrame = statusArray.first{
            
                params["since_id"] = "\(statusFrame.status!.id)"
            }
        }
        
        ZHLEENetWorkTools.request(.GET,url:urlString, params: params, success: { (result) -> () in

                //status字典数组
                let statusDictArr = result["statuses"] as? [[String: AnyObject]]
                //临时数组
                var tempArr = [ZHLEEStatusFrame]()
                
                for statuDict in statusDictArr! {
                    
                    let status = ZHLEEStatus(dictionary: statuDict)
                    
                    let statusFrame = ZHLEEStatusFrame()
                    statusFrame.status = status
                    
                    tempArr.append(statusFrame)
                }
                if self.statusArray.count > 0{
                    self.showPullDownTips(tempArr.count)
                }
                //是否是上拉刷新
                if self.pullupView.isAnimating(){
                    
                    self.statusArray += tempArr
                    
                }else{
                    
                    self.statusArray = tempArr + self.statusArray
                }
                self.tableView.reloadData()
            //停止加载动画
            self.endRefreShing()
            }) { (error) -> () in
                printLog("错误信息:\(error)")
                SVProgressHUD.showInfoWithStatus("请求失败!你的网络有问题!")
                
                self.endRefreShing()
        }
        
    }
    
    private func endRefreShing(){
    
        self.pullupView.stopAnimating()
        self.refreshControl?.endRefreshing()
    }
    
    private func showPullDownTips(count : Int){
    
        if !pullDownTipLabel.hidden{
        
            return
        }
        
        pullDownTipLabel.text = count == 0 ? "没有新的微博信息" : "\(count)条新微博信息"
        self.navigationController!.view.insertSubview(pullDownTipLabel, belowSubview: self.navigationController!.navigationBar)
        
        //设置大小\位置,并显示
        let height: CGFloat = 35
        
        pullDownTipLabel.size = CGSizeMake(ScreenW, height)
        pullDownTipLabel.hidden = false
        pullDownTipLabel.y = CGRectGetMaxY((self.navigationController?.navigationBar.frame)!) - height
        
        //执行动画
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            //调整y为pullDownTipLabel的
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, height)
            
            }) { (finished) -> Void in
            
                UIView.animateKeyframesWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    //清空动画
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (finished) -> Void in
                        
                        self.pullDownTipLabel.hidden = true
                })
        }
    }
    
    //设置nav上左右两个按钮
    private func setNavItem(){
    
        let popPicName = "navigationbar_pop"
        let friendsPicName = "navigationbar_friendsearch"
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.item(self, action: "push", imageName: popPicName)
        navigationItem.leftBarButtonItem = UIBarButtonItem.item(self, action: "push", imageName: friendsPicName)
        
        setTitleButton()
        
    }
    private func setTitleButton(){
    
        let titleButton = ZHLEETitleButton()
        
        titleButton.addTarget(self, action: "titleButtonDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        titleButton.setTitle("首页", forState: UIControlState.Normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Selected)
        
        titleButton.setTitleColor(RGB(r: 80, g: 80, b: 80), forState: .Normal)
        
        titleButton.sizeToFit()
        
        navigationItem.titleView = titleButton
        
        
    }
    
    @objc private func titleButtonDidClick(button: UIButton){
    
//        printLog("titleBtn did click")
        button.selected = !button.selected
        
        //添加一个遮罩
        let contentView = UIView()
        contentView.size = CGSizeMake(150, 150)
        contentView.backgroundColor = UIColor.redColor()
        
        let view = ZHLEEPopBtnView(customView: contentView)
        view.block = {void in
        
            button.selected = !button.selected
        }
        view.show(button)
        
    }
    
    @objc private func push(){
        
        navigationController?.pushViewController(ZHLEETempViewVC(), animated: true)
        
    }
}
// MARK: - 维护tableView的data source 以及 delegate
extension ZHLEEHomeViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusArray.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(Cell_ID, forIndexPath: indexPath) as! ZHLEEStatusCell
        
        cell.statusFrame = statusArray[indexPath.row]
        
        if indexPath.row == statusArray.count - 1 && !pullupView.isAnimating(){
        
            printLog("加载更多")
            
            pullupView.startAnimating()
            
            loadData()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return statusArray[indexPath.row].cellHeight
    }
}
